<template>
  <div>
    <svg-icon icon-class="problem" size="small" class="navSvgSty" @click="openDialog()" />
    <el-dialog title="问题反馈" :visible.sync="showProblem" :destroy-on-close="false" convert-record :append-to-body="true" view-crash-manage class="problem_dialog" :close-on-click-modal="false">
      <el-form ref="form" size="small" label-width="80px" label-position="left" :rules="rules" :model="formData" :inline="true">
        <el-form-item label="所属模块" prop="module">
          <el-select v-model="formData.module" filterable placeholder="请选择" style="width: 240px">
            <el-option v-for="item in dict.feedback_module" :key="item.id" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="问题描述" prop="description">
          <el-input
            v-model="formData.description"
            type="textarea"
            :autosize="{ minRows: 6, maxRows: 80}"
            maxlength="1000"
            minlength="1"
            show-word-limit
            style="width: 460px"
          />
        </el-form-item>
        <el-form-item label="问题截图" prop="file">
          <el-upload
            ref="upload"
            :multiple="true"
            :on-remove="handleRemove"
            :limit="limit"
            :headers="headers"
            style="margin-top: 5px;display: inline-block;"
            :accept="acceptFile('img')"
            action
            :auto-upload="false"
            list-type="picture-card"
            :on-exceed="handleExceed"
            :before-upload="beforeUpload"
            :file-list="fileList"
            :on-change="handleChange"
            :on-error="uploadError"
          >
            <i class="el-icon-plus" />
            <div slot="tip" class="el-upload__tip">上传文件只能是 png/jpg/jpeg/gif 格式，且不能超过6张！</div>
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="text" @click="dialogClose">取消</el-button>
        <el-button type="primary" :loading="isLoading" @click="submitFile">确认</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getToken } from '../../utils/auth'
import { setLoading } from '../../utils'
import { add } from '../../api/feedback.js'
import { mapGetters } from 'vuex'
export default {
  name: 'Feedback',
  dicts: ['feedback_module'],
  data() {
    this.setLoading = setLoading.bind(this)
    return {
      uploadFormData: {},
      isLoading: false, // 按钮加载状态
      formData: {
        description: '',
        module: ''
      },
      ticket_url: '', // 问题反馈链接
      showProblem: false,
      limit: 6,
      headers: {
        'Authorization': getToken()
      },
      fileList: [],
      rules: {
        description: [
          { required: true, message: '问题描述不能为空', trigger: 'blur' },
          { min: 1, max: 1000, message: '长度在 1 到 1000 个字符', trigger: 'blur' }
        ],
        module: [
          { required: true, message: '模块不能为空', trigger: 'blur' }
        ]
      }
    }
  },
  computed: {
    ...mapGetters([
      'user'
    ])
  },
  methods: {
    openDialog() {
      // 拼接角色
      let role = ''
      this.user.roles.forEach(item => {
        if (role !== '') {
          role = role + ',' + item.name
        } else {
          role = item.name
        }
      })
      // 点击问题反馈 跳转到相应url 云工场平台(0) 项目管理模块(1) 设计库模块(2) HUB模块(3) 其他(4)
      this.ticket_url = JSON.parse(localStorage.getItem('messageStore')).ticket_url.value + 'module=1' + '&site=' + decodeURI(this.user.site.name) + '&sponsor_role=' + decodeURI(role)
      window.open(this.ticket_url, '_blank')
      // this.showProblem = true
    },
    handleChange(file, fileList) {
      const existFile = fileList.slice(0, fileList.length - 1).find(f => f.name === file.name)
      if (existFile) {
        this.$message.error('当前文件已经存在!')
        fileList.pop()
      }
      this.fileList = fileList
    },
    /* 移除上传列表中文件*/
    handleRemove(file, fileList) {
      this.fileList = fileList
    },
    /* 图片上传超过数量限制*/
    handleExceed(file, fileList) {
      this.$message.error('上传图片不能超过' + this.limit + '张!')
    },
    /* 上传图片*/
    uploadError(err, file, fileList) {
      this.$message.error(err)
    },
    /* 文件格式*/
    acceptFile(e) {
      const allowHook = {
        video: '.mp4, .ogv, .ogg, .webm',
        audio: '.wav, .mp3, .ogg, .acc, .webm, .amr',
        file: 'doc,.docx,.xlsx,.xls,.pdf',
        excel: 'xlsx,.xls',
        img: '.jpg, .jpeg, .png, .gif'
      }
      if (e) {
        return allowHook[e]
      }
      let srt = null
      for (const k in allowHook) {
        srt += allowHook[k]
      }
      return srt
    },
    /* 开始上传前验证*/
    beforeUpload(file) {
      /* 验证文件类型*/
      if (file.name) {
        var testmsg = file.name.substring(file.name.lastIndexOf('.') + 1)
        const extension = testmsg === 'png' || testmsg === 'jpg' || testmsg === 'jpeg' || testmsg === 'gif'
        if (!extension) {
          this.$message.error('上传格式错误')
        }
        return extension
      }
      /* 验证文件大小*/
      /*     if (file.size / 1024 / 1024 > this.formMaxSize) {
        this.$message({
          message: '文件大小不能超过' + this.formMaxSize + 'M！',
          type: 'warning'
        })
        return false
      }*/
    },
    /* 点击按钮触发上传前校验*/
    submitFile() {
      this.$refs.form.validate(valid => {
        if (valid) {
          this.setLoading(true)
          this.uploadFormData = new FormData()
          this.uploadFormData.append('description', this.formData.description)
          this.uploadFormData.append('module', this.formData.module)
          for (let i = 0; i < this.fileList.length; i++) {
            this.uploadFormData.append('file' + (i + 1).toString(), this.fileList[i].raw)
          }
          add(this.uploadFormData).then((data) => {
            if (data) {
              this.setLoading(false)
              this.fileList = []
              this.formData.module = ''
              this.formData.description = ''
              this.dialogClose()
            }
          }).catch(() => {
            this.setLoading(false)
          })
        } else {
          return false
        }
      })
    },
    dialogClose() {
      this.showProblem = false
    }
  }
}
</script>
<style lang="scss" scoped>
.el-form-item{
  padding: 0 0px 0 20px;
}
</style>
<style lang="scss">
.problem_dialog[view-crash-manage] {
  .el-dialog {
    line-height: 24px;
    font-style: revert;
    width: 640px;
    max-height: 90%;
    height: auto;
    padding: 0;
    .el-dialog__title{
      font-size: 18px;
      color: var(--brother-common-tips-text-color);
      padding-top: 20px;
    }
    .el-dialog__header{
      padding: 20px;
      padding-bottom: 10px;
    }
    .el-dialog__body{
      padding: 30px 20px;
    }
  }
}
</style>
